package com.ctlele.team.space.util;

import android.graphics.BitmapFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class InputStreamUtils {

    public static final byte[] NULL = new byte[0];

    public static byte[] readStream(InputStream stream) throws IOException {
        return readStream(stream, 1024 * 1024 * 5);
    }

    public static byte[] readStream(InputStream stream, int bufSize) throws IOException {
        byte[] buffer = new byte[bufSize];
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int readSize;
        while ((readSize = stream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, readSize);
        }
        return outputStream.toByteArray();
    }

    public static byte[] copyArray(byte[] source) {
        byte[] copy = new byte[source.length];
        System.arraycopy(source, 0, copy, 0, source.length);
        return copy;
    }

    public static InputStream openHttpStream(String url) {
        try {
            URL fromUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) fromUrl.openConnection();
            connection.setRequestMethod("GET");
            int code = connection.getResponseCode();

            if (code == 200) {
                return connection.getInputStream();
            } else {
                return new ByteArrayInputStream(NULL);
            }
        } catch (Exception e) {
            return new ByteArrayInputStream(NULL);
        }
    }
}
